package com.rzico.sbl.ui.mine

import com.lzy.okgo.utils.OkLogger
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityInfoBinding
import com.rzico.sbl.model.BaseUrl
import com.rzico.sbl.other.showMemoDialog
import com.rzico.sbl.other.showQrcodeDialog
import com.rzico.sbl.picture.buildSelectionModel
import com.rzico.sbl.picture.callback
import com.rzico.sbl.ui.LoginActivity
import com.tim.library.logout
import com.xinnuo.common.extend.get
import com.xinnuo.common.extend.notEmpty
import com.xinnuo.common.extend.oneClick
import com.xinnuo.common.extend.optNotNull
import com.xinnuo.common.extend.startActivityEx
import com.xinnuo.common.helper.clearShared
import com.xinnuo.common.helper.getString
import com.xinnuo.common.helper.phoneReplaceWithStar
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.glideExt.loadCircleImage
import com.xinnuo.common_ui.oss.OSSHelper
import com.xinnuo.common_ui.utils.showHintDialog
import org.json.JSONObject

class InfoActivity : BaseActivity(R.layout.activity_info) {

    private val mBinding by lazy { ActivityInfoBinding.bind(getRootView()) }
    private var mUserName = ""
    private var mUserLogo = ""

    override fun getViewModel() = get<MineViewModel>()

    override fun initData() {
        initTitle(title = "个人信息")
        observeData()

        getViewModel().mineInfo(true)
    }

    override fun initListener() {
        mBinding.apply {
            infoImgLl.oneClick {
                buildSelectionModel()
                    .callback {
                        onResult {
                            it.notEmpty {
                                val media = this.first()

                                OSSHelper
                                    .manager
                                    .uploadSingleImage(
                                        path = if (media.isCompressed) media.compressPath else media.cutPath,
                                        onBefore = { showLoading("正在上传中...") },
                                        onAfter = { dismissLoading() },
                                        onSuccess = { result ->
                                            val mUrl = result.responseHeader["url"].orEmpty()

                                            getViewModel()
                                                .request(
                                                    requestUrl = BaseUrl.mineUpdate,
                                                    params = arrayOf("logo" to mUrl),
                                                    onSuccess = {
                                                        showToast("头像修改成功！")

                                                        mUserLogo = mUrl
                                                        mBinding
                                                            .infoImg
                                                            .loadCircleImage(
                                                                mUserLogo,
                                                                R.mipmap.default_user
                                                            )
                                                    }
                                                )
                                        },
                                        onError = { showToast("网络异常，请稍候再试！") }
                                    )
                            }
                        }
                    }
            }

            infoName.oneClick {
                showMemoDialog(
                    title = "修改昵称",
                    hint = "请输入昵称(10个汉字以内)",
                    default = mUserName,
                    inputType = "text",
                    canEmpty = false
                ) { result ->
                    getViewModel()
                        .request(
                            requestUrl = BaseUrl.mineUpdate,
                            isMultipart = true,
                            params = arrayOf("nickName" to result),
                            onSuccess = {
                                showToast("昵称修改成功！")

                                mUserName = result
                                mBinding.infoName.setRightString(mUserName)
                            }
                        )
                }
            }

            infoQrcode.oneClick { showQrcodeDialog(mUserName, mUserLogo) }

            // infoPhone.oneClick { startActivityEx<InfoPhoneActivity>() }

            infoPwd.oneClick { startActivityEx<InfoPasswordActivity>() }

            infoCancel.oneClick {
                showHintDialog(
                    title = "注销账户",
                    hint = "确定要注销该账户吗？",
                    sure = "注销",
                    onSure = {
                        getViewModel()
                            .request(
                                requestUrl = BaseUrl.mineLogout,
                                onSuccess = {
                                    showToast("账户注销成功！")

                                    when (getString("shopStatus")) {
                                        "success" -> logout {
                                            onSuccess {
                                                OkLogger.i("腾讯云即时通讯退出登录！")
                                                clearShared("phone", "loginMode")
                                                startActivityEx<LoginActivity>("offLine" to true)
                                            }
                                        }

                                        else -> {
                                            clearShared("phone")
                                            startActivityEx<LoginActivity>("offLine" to true)
                                        }
                                    }
                                }
                            )
                    }
                )
            }
        }
    }

    /**
     * 观察个人信息数据
     */
    private fun observeData() {
        getViewModel()
            .mInfoEvent
            .observe(this) { result ->
                val obj = JSONObject(result)

                mUserName = obj.optNotNull("nickName")
                mUserLogo = obj.optNotNull("logo")

                mBinding.infoImg.loadCircleImage(mUserLogo, R.mipmap.default_user)
                mBinding.infoName.setRightString(mUserName)
                mBinding.infoLogin.setRightString(obj.optNotNull("userId"))
                mBinding.infoPhone.setRightString(obj.optNotNull("mobile").phoneReplaceWithStar())
            }
    }

}